import urllib.request
import json
import logging
import os
import time
import threading
import sys

#全局配置
url_trackers_best = "https://raw.githubusercontent.com/ngosang/trackerslist/master/trackers_best.txt"
aria2_config = "/home/pi/.config/aria2/aria2.config"
logFile = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logger.log')

# 配置日志参数
logging.basicConfig(filename=logFile,
                    format="%(asctime)s \n%(message)s",
                    datefmt="%Y-%m-%d %H:%M:%S",
                    filemode='w',
                    level=40)


def log(level, message):
    "写日志"
    logging.log(level, message)
    return


def getTrackers(url):
    "更新Trackers"
    t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    log(logging.DEBUG, "更新Trackers【开始】{0}\n url = {1}".format(
        t, url))
    try:
        # 获取最新数据
        pwdmgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
        auth_handler = urllib.request.HTTPBasicAuthHandler(pwdmgr)
        opener = urllib.request.build_opener(auth_handler)
        response = opener.open(url)
        result = response.read().decode('utf-8')
        result = str.strip(result)
        trackers = list(filter(lambda l: len(l) > 0, str.splitlines(result)))
        allTrackers = ",".join(trackers)

        log(logging.DEBUG, "更新Trackers【结束】{0}".format(result))
        return allTrackers
    except BaseException as e:
        log(logging.ERROR, "更新Trackers【异常】{0}".format(e))
        return None


def upDateConfig(allTrackers):
    "更新aria2.config文件  bt-tracker=allTrackers"
    try:
        btTrackerIndex = -1
        cfgList = list()
        with open(aria2_config, "r", encoding='utf8') as cfgFile:
            lines = cfgFile.readlines()
            cfgList = list(lines)
            for line in cfgList:
                if (line.startswith("bt-tracker=")):
                    btTrackerIndex = cfgList.index(line)
                    break
            if (btTrackerIndex >= 0):
                cfgList.pop(btTrackerIndex)
                if (btTrackerIndex - 1 >= 0 and cfgList[btTrackerIndex - 1].startswith("#更新于")):
                    cfgList.pop(btTrackerIndex - 1)
                    btTrackerIndex = btTrackerIndex - 1
            else:
                btTrackerIndex = 0

        cfgList.insert(btTrackerIndex, "bt-tracker="+allTrackers+"\n")
        upDateTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        cfgList.insert(btTrackerIndex, "#更新于"+upDateTime+"\n")

        with open("aria2.config", "w", encoding='utf8') as cfgFile:
            cfgFile.writelines(cfgList)

        return True
    except BaseException as e:
        log(logging.ERROR, "更新aria2.config文件【异常】{0}".format(e))
        return False

def reSetConfig():
    "aria2c --conf-path=/home/pi/.config/aria2/aria2.config"
    try:
        os.system("aria2c --conf-path=" + aria2_config)
    except BaseException as e:
        log(logging.ERROR, "重新载入配置文件【异常】{0}".format(e))
        return False


# 配置日志输出级别
logger = logging.getLogger()
logger.setLevel(logging.ERROR)

# 开始更新操作
log(logging.DEBUG, "开始更新操作【开始】")
allTrackers = getTrackers(url_trackers_best)
upDateConfig(allTrackers)
reSetConfig()
log(logging.DEBUG, "开始更新操作【结束】\n")